import { Role } from "@mallfoundry/store/role"
import { Button, Form, Input, Space } from "antd"
import * as _ from "lodash"
import * as React from "react"
import { useEffect, useState } from "react"
import RoleAuthorities from "./role-authorities"

interface RoleFormProps {
  loading: boolean
  role: Role
  onFinish?: (role: Role) => void
  onCancel?: () => void
}

export default function RoleForm(props: RoleFormProps) {
  const { loading, role, onFinish: finish, onCancel } = props
  const layout = { labelCol: { span: 2 }, wrapperCol: { span: 4 } }
  const tailLayout = { wrapperCol: { offset: 2, span: 16 } }
  const [authorities, setAuthorities] = useState([] as string[])

  const onFinish = (values: Role) => {
    if (_.isFunction(finish)) {
      finish(_.assign(new Role(), role, values, { authorities }))
    }
  }

  const [form] = Form.useForm()
  useEffect(() => {
    form.setFieldsValue(role)
    setAuthorities(role.authorities as string[])
  }, [form, role])

  return (
    <Form {...layout} form={form} onFinish={onFinish}>
      <Form.Item label="角色名称" name="name">
        <Input/>
      </Form.Item>
      <Form.Item label="角色描述" name="description">
        <Input.TextArea autoSize={{ minRows: 2, maxRows: 6 }}/>
      </Form.Item>
      <Form.Item label="权限">
        <RoleAuthorities authorities={authorities} onChange={setAuthorities}/>
      </Form.Item>
      <Form.Item {...tailLayout}>
        <Space>
          <Button type="primary" htmlType="submit" loading={loading}>保存</Button>
          <Button htmlType="button" onClick={onCancel}>取消</Button>
        </Space>
      </Form.Item>
    </Form>
  )
}
